package com.gitee.huanminabc.fastboot.load.stage;

import com.gitee.huanminabc.jcommon.multithreading.executor.ThreadFactoryUtil;
import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.context.AppContextUtil;
import com.gitee.huanminabc.fastboot.load.stage.prestage.AppLoadPreStage;
import com.gitee.huanminabc.fastboot.load.stage.prestage.BytebuddyPreload;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @description:
 * @author: huanmin
 * @create: 2025-04-08 18:30
 **/
@Slf4j
public class PreStageLauncher  {
    public final static List<AppLoadPreStage> appLoadStages = new ArrayList<>();
    static {
        if (AppContext.appBaseInfoConfig.getAop()){
            // 预加载阶段
            appLoadStages.add(new BytebuddyPreload());
        }

    }

    public void load() {
        AppContextUtil.orderSort(appLoadStages);
        ThreadPoolExecutor executor = ThreadFactoryUtil.getDefaultExecutor();
        for (AppLoadStage appLoadStage : appLoadStages) {
            if (!appLoadStage.isRun()) {
                continue;
            }
            //异步加载
            executor.execute(() -> {
                AppContext.taskTimeWatch.start(appLoadStage.getClass().getSimpleName() + "耗时");
                try {
                    appLoadStage.run();
                } catch (Exception e) {
                    log.error("PreStageLauncher:", e);
                    System.exit(1);
                } finally {
                    AppContext.taskTimeWatch.stop();
                }
            });
        }
    }
}
